/**
* @fileOverview 路由菜单
* @author wind-lc
* @version 1.0
*/

import { constantRoutes } from '@/router/index'
import { filterRoute, getSessionStorage, setSessionStorage } from '@/utils'

// 初始数据
const state = {
  routes: getSessionStorage('isadjjjnh3wdw') ? getSessionStorage('isadjjjnh3wdw') : []
}
// 修改state数据
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}
// 监听state数据变化(最新状态)
const getters = {
  getRoutes (state) {
    return state.routes
  }
}
// 触发mutations里的方法
const actions = {
  // 生成路由菜单
  generateRoutes ({ dispatch, commit }, data) {
    return new Promise((resolve, reject) => {
      let path = []
      dispatch('getInfo').then(res => {
        path = res.menuList.map(el => {
          if (el.children && (el.children.length > 0)) {
            const menu = []
            el.children.forEach(item => {
              menu.push(item.resValue)
            })
            return [el.resValue, ...menu]
          } else {
            return el.resValue
          }
        }).flat()
        const accessedRouters = filterRoute(path, (() => {
          let el = {}
          constantRoutes.forEach(item => {
            if (item.path === '/') {
              el = item
            }
          })
          return el
        })())
        commit('SET_ROUTES', accessedRouters)
        setSessionStorage('isadjjjnh3wdw', accessedRouters)
        resolve(accessedRouters)
      }).catch(error => {
        reject(error)
      })
    })
  }
}
export default { state, getters, mutations, actions }
